package cn.com.zd.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.interfaces.JWTPartsParser;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {
    private static final String secretKey = "12@@##3456";
    public static void main(String[] args) {
        long expire = System.currentTimeMillis();
        String userId = "171";

        // 设置头部信息
        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("typ","JWT");
        headerMap.put("alg","alg");
        com.auth0.jwt.JWTCreator.Builder builder = JWT.create()
                .withHeader(headerMap)
                .withClaim("expire", expire)
                .withClaim("exp", expire)
                .withClaim("userId", userId);

        // 设置过期时间
        Date expirationDate = new Date(expire * 1000);
        builder.withExpiresAt(expirationDate);

        // 签名
        Algorithm algorithm = Algorithm.HMAC256(secretKey);
        String token = builder.sign(algorithm);

        System.out.println("JWT Token: " + token);

        // 验证Token
        JWTVerifier verifier = JWT.require(algorithm).build();
        try {

            DecodedJWT jwt = verifier.verify(token);
            System.out.println("Token验证成功，解码信息如下:");
            System.out.println("Header: " + jwt.getHeader());
            System.out.println("Payload: " + jwt.getPayload());
        } catch (JWTVerificationException exception) {
            System.out.println("Token验证失败: " + exception.getMessage());
        }
        // 使用封装的方法
        String token1 = doCreateToken("hahaha", new Date());
        System.out.println(token1);
        System.out.println(verifyToken(token1));
    }
    private static String doCreateToken(String data,Date date) {
        Algorithm algorithm = Algorithm.HMAC256(secretKey);
        JWTCreator.Builder builder = JWT.create();
        return builder.withClaim("data",data)
                .withClaim("expire",date)
                .withExpiresAt(date)
                .sign(algorithm);
    }
    private static Boolean verifyToken(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secretKey);

            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT verify = verifier.verify(token);
            // 如果不需要验证，可直接从token中截取，使用“\\.”分割
            System.out.println("claims(payload):\t" + verify.getClaims());
            System.out.println("header:\t" + verify.getHeader());
            System.out.println("HeaderJSON: " + new String(Base64.getDecoder().decode(verify.getHeader())));

            System.out.println("payload:\t" + verify.getPayload());
            System.out.println("PayloadJSON: " + new String(Base64.getDecoder().decode(verify.getPayload())));

            System.out.println("token:\t" + verify.getToken());
            System.out.println("signature:\t" + verify.getSignature());
            return Boolean.TRUE;
        }catch (AlgorithmMismatchException e) {
            e.printStackTrace();
        }
        return Boolean.FALSE;
    }
}
